<!--  -->
<template>
  <el-dialog
    :title="title"
    :visible="isShow"
    :width="dialogWidth"
    :before-close="handleClose"
    :close-on-click-modal="false"
    top="8vh"
    destroy-on-close
  >
    <div class="dialog-container">
      <!-- form表单、查询按钮 -->
      <div class="flex-row justify-between align-center w-100P ">
        <el-form ref="form" :model="queryInfo" label-width="80px" inline>
          <el-form-item label="所属组织" v-if="isPerson">
            <el-select
              v-model="queryInfo.recordsPersonVo.orgId"
              clearable
              placeholder="请选择所属组织"
            >
              <el-option
                v-for="item in orgList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-input
              v-model="queryInfo.keyword"
              placeholder="请输入人员姓名"
              suffix-icon="el-icon-search"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-button type="info" @click.stop="getTableData">查询</el-button>
      </div>
      <div class="table-container ">
        <!-- table表格 -->
        <el-table
          ref="table"
          v-loading="loading"
          :data="tableData"
          height="88%"
          :cell-style="{ background: '#fff' }"
          header-cell-class-name="table-header-cell"
          header-row-class-name="table-header-row"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="handleSelectable"
          ></el-table-column>

          <el-table-column prop="fileId" :label="imgLabel" width="100">
            <template v-slot="{ row }">
              <div :class="{'no-selectable': !handleSelectable(row)}">
                <img v-if="row.fileId" class="avatar-img" :src="row.fileId | imageFormat" alt="" />
                <svg-icon v-else class="avatar-img" icon-class="person-icon"></svg-icon>
              </div>
            </template>
          </el-table-column>

          <template v-if="isPerson">
            <el-table-column prop="name" label="人员姓名">
              <template v-slot="{ row }">
                <span :class="{'no-selectable': !handleSelectable(row)}">{{row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="orgName" label="所属组织">
              <template v-slot="{ row }">
                <span :class="{'no-selectable': !handleSelectable(row)}">{{row.orgName}}</span>
              </template>
            </el-table-column>
          </template>

          <template v-else>
            <el-table-column prop="carNo" label="车牌号" />
            <el-table-column prop="personName" label="车主名称" />
          </template>

          <el-table-column prop="id" label="最近通行记录">
            <template v-slot="{ row }">
              <div class="flex-row align-center" :class="{'no-selectable': !handleSelectable(row)}">
                <div v-if="row.accessControlLogVO">
                  {{row.accessControlLogVO.createTime | dateTimeFormatter}}
                </div>
                <div
                  v-if="row.accessControlLogVO && row.accessControlLogVO.deviceVO"
                  class="mg-left-8"
                >
                  {{row.accessControlLogVO.deviceVO.remarkName}}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          hide-on-single-page
          background
          layout="prev, pager, next, total, jumper"
          :total="total"
          :page-size="queryInfo.pageSize"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    <div slot="footer" class="dialog-footer w-100P">
      <div class="flex-row justify-between align-center w-100P">
        <div class="fz-14" style="color: #333;">
          已选择
          <span class="fz-20 mg-lr-3" style="color: #D12D1F;">{{selectCount}}</span>
          名人员
        </div>
        <div>
          <el-button :loading="isLoading" type="primary" size="small" @click="handleSubmit">
            确认
          </el-button>
          <el-button size="small" @click="handleClose">取 消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { handleScreenWidthToVw } from '@/utils/tools'
import { findOrgList } from '@/views/user/api'
import { apiGetPersonList, apiPullBlackList, apiGetCardList, apiPullCarBlackList } from '../api'
import pullAll from 'lodash/pullAll'

const IDENTITY_ENUM = {
  INTERNAL_MEMBER: 'INTERNAL_MEMBER',
  VISITOR: 'VISITOR',
}

export default {
  props: {
    isShow: { type: Boolean, default: false },
    identityEnum: { type: String, default: '' },
    isPerson: { type: Boolean, default: true },
  },
  data() {
    return {
      title: '',
      isLoading: false,
      queryInfo: {
        recordsPersonVo: {
          orgId: null,
          identityEnum: null,
        },
        recordsCarVo: {
          identityEnum: null,
        },
        keyword: '',
        pageNo: 1,
        pageSize: 8,
      },
      orgList: [],
      tableData: [],
      total: 0,
      loading: false,
      selectList: [],
      currentSelectList: [],
    }
  },

  created() {
    this.isPerson ? delete this.queryInfo.recordsCarVo : delete this.queryInfo.recordsPersonVo
  },

  watch: {
    identityEnum: {
      immediate: true,
      handler(newValue) {
        if (!newValue) return
        const name = this.isPerson ? '人员' : '车辆'
        switch (newValue) {
          case IDENTITY_ENUM.INTERNAL_MEMBER:
            this.title = `添加园内${name}至黑名单`
            break
          case IDENTITY_ENUM.VISITOR:
            this.title = `添加访客${name}至黑名单`
            break
        }

        this.isPerson
          ? (this.queryInfo.recordsPersonVo.identityEnum = newValue)
          : (this.queryInfo.recordsCarVo.identityEnum = newValue)

        this.handleReset()
      },
    },
    isPerson(newValue) {
      this.handleReset()
      newValue && this.getOrgList()
    },
  },

  components: {},

  computed: {
    dialogWidth() {
      return `${handleScreenWidthToVw(1092)}px`
    },
    selectCount() {
      return this.selectList.length + this.currentSelectList.length
    },
    imgLabel() {
      return this.isPerson ? '头像' : '车牌照'
    },
  },

  mounted() {
    this.isPerson && this.getOrgList()
  },

  methods: {
    handleClose() {
      this.$emit('close')
    },
    async handleSubmit() {
      // TODO 提交添加
      try {
        const currentIdList = this.currentSelectList.map(item => item.id)
        this.selectList = [...this.selectList, ...currentIdList]
        this.isPerson
          ? await apiPullBlackList(this.selectList)
          : await apiPullCarBlackList(this.selectList)
        this.handleReset()
        this.$message.success('添加成功！')
        this.$emit('add')
      } catch (error) {
        console.log('apiPullBlackList request error', error)
      }
    },
    async getOrgList() {
      try {
        const res = await findOrgList()

        this.orgList = res || []
      } catch (error) {
        console.log('findOrgList request error', error)
      }
    },
    async getTableData() {
      // TODO 查询
      try {
        // 将当前选择的选项保存
        const currentIdList = this.currentSelectList.map(item => item.id)
        this.selectList = [...this.selectList, ...currentIdList]
        this.currentSelectList = []
        const res = this.isPerson
          ? await apiGetPersonList(this.queryInfo)
          : await apiGetCardList(this.queryInfo)
        this.total = res.total || 0
        this.tableData = res.records || []

        // 选项勾选恢复
        this.$nextTick(() => {
          const spliceId = []

          this.tableData.forEach(item => {
            if (this.selectList.includes(item.id)) {
              this.$refs.table.toggleRowSelection(item, true)
              spliceId.push(item.id)
            }
          })

          this.selectList = pullAll(this.selectList, spliceId)
        })
      } catch (error) {
        console.log(`apiGetPersonList request error`, error)
      }
    },
    handlePageChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.getTableData()
    },

    handleSelectable(item) {
      if (item && item.black) {
        return false
      }
      return true
    },
    handleSelectionChange(selectList) {
      this.currentSelectList = selectList
    },
    handleReset() {
      this.$refs.form && this.$refs.form.resetFields()
      this.tableData = []
      this.total = 0
      this.selectList = []
      this.currentSelectList = []
    },
  },
}
</script>
<style lang='scss' scoped>
.dialog-container {
  display: flex;
  flex-direction: column;
  // align-items: center;
  // justify-content: center;
  height: 70vh;
}

.dialog-children {
  flex-shrink: 0;
}

::v-deep {
  .table-header-cell {
    color: #333;
    background: #f0f4f8 !important;
  }

  .el-table td,
  .el-table th {
    padding: vh(10px) 0;
  }

  .el-dialog__body {
    padding: vw(20px) vh(20px);
  }

  .el-dialog__footer {
    padding: 0 vw(20px) vw(20px) vh(20px);
  }
}

.avatar-img {
  width: vh(30px);
  height: vh(30px);
}

.enter-text {
  color: #67c337;
}

.table-container {
  height: vh(662px);
  border: 1px solid #ccc;
}

.no-selectable {
  opacity: 0.33;
}
</style>
